<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="custom-nav">
      <!-- <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view> -->
      <view class="user-info" @click="goToUserDetail">
        <image 
          :src="targetUser.avatar" 
          mode="aspectFill"
          class="avatar"
        ></image>
        <view class="name-info">
          <view class="name">{{ targetUser.nickname }}</view>
          <view class="status" v-if="targetUser.isOnline">在线</view>
          <view class="status" v-else>离线 · {{ targetUser.lastOnline }}</view>
        </view>
      </view>
      <view class="more-btn">
        <uni-icons type="ellipsis" size="20" color="#333"></uni-icons>
      </view>
    </view>
    
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-content" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      @scrolltolower="loadMoreMessages"
      :style="{ height: contentHeight + 'px' }"
    >
      <!-- 日期分隔线 -->
      <view class="date-separator" v-if="showDateSeparator">
        {{ currentDate }}
      </view>
      
      <!-- 消息列表 -->
      <view class="message-list">
        <!-- 对方消息 -->
        <view 
          class="message-item other" 
          v-for="(message, index) in messageList" 
          :key="message.id"
          :class="{ 'show-timestamp': showTimestamp(index) }"
        >
          <image 
            :src="targetUser.avatar" 
            mode="aspectFill"
            class="avatar"
          ></image>
          <view class="message-content">
            <view class="timestamp" v-if="showTimestamp(index)">
              {{ formatTime(message.timestamp) }}
            </view>
            <view class="bubble">
              {{ message.content }}
            </view>
          </view>
        </view>
        
        <!-- 自己的消息 -->
        <view 
          class="message-item mine" 
          v-for="(message, index) in messageList" 
          :key="message.id"
          :class="{ 'show-timestamp': showTimestamp(index) }"
        >
          <view class="message-content">
            <view class="timestamp" v-if="showTimestamp(index)">
              {{ formatTime(message.timestamp) }}
            </view>
            <view class="bubble">
              {{ message.content }}
            </view>
            <view class="status" v-if="message.status === 'sending'">
              <uni-icons type="loading" size="14" color="#999"></uni-icons>
            </view>
            <view class="status" v-if="message.status === 'failed'">
              <uni-icons type="close" size="14" color="#FF4500"></uni-icons>
            </view>
          </view>
          <image 
            :src="currentUser.avatar" 
            mode="aspectFill"
            class="avatar"
          ></image>
        </view>
      </view>
      
      <!-- 加载历史消息提示 -->
      <view class="loading-history" v-if="loadingHistory">
        加载历史消息...
      </view>
      
      <!-- 没有更多历史消息 -->
      <view class="no-more-history" v-if="!loadingHistory && !hasMoreHistory">
        已经是最早的消息了
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area" :style="{ bottom: keyboardHeight + 'px' }">
      <!-- <view class="toolbar">
        <view class="tool-btn" @click="toggleEmojiPanel">
          <uni-icons type="emoji" size="22" color="#666"></uni-icons>
        </view>
        <view class="tool-btn" @click="chooseImage">
          <uni-icons type="camera" size="22" color="#666"></uni-icons>
        </view>
        <view class="tool-btn" @click="takePhoto">
          <uni-icons type="camera-filled" size="22" color="#666"></uni-icons>
        </view>
      </view> -->
      
      <view class="input-box">
        <input 
          type="text" 
          placeholder="请输入消息..." 
          v-model="inputMessage"
          @focus="onInputFocus"
          @confirm="sendMessage"
          :adjust-position="false"
          :confirm-type="confirmType"
        >
      </view>
      
      <view class="send-btn" @click="sendMessage">
        发送
      </view>
    </view>
    
    <!-- 表情面板 -->
    <!-- <view class="emoji-panel" v-show="emojiPanelVisible">
      <view class="emoji-row" v-for="(row, rowIndex) in emojiRows" :key="rowIndex">
        <view 
          class="emoji-item" 
          v-for="(emoji, emojiIndex) in row" 
          :key="emojiIndex"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </view>
      </view>
    </view> -->
  </view>
</template>

<script>
import mockChatData from '../../mock/chatData'

export default {
  data() {
    return {
      targetUser: {
		  avatar:'https://picsum.photos/id/237/200/200',
		  nickname:'才十块',
		  isOnline:true
	  },
      currentUser: {
		  avatar:'https://picsum.photos/id/237/200/200',
		  nickname:'才十块',
		  isOnline:false
	  },
      messageList: [],
      inputMessage: '',
      emojiPanelVisible: false,
      keyboardHeight: 0,
      scrollTop: 0,
      contentHeight: 0,
      loadingHistory: false,
      hasMoreHistory: true,
      page: 1,
      pageSize: 20,
      showDateSeparator: true,
      currentDate: ''
      // emojiList: [
      //   '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
      //   '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
      //   '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
      //   '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
      //   '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬',
      //   '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗',
      //   '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯',
      //   '😦', '😧', '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐',
      //   '🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕', '🤑', '🤠', '😈',
      //   '👿', '👹', '👺', '💀', '👻', '👽', '🤖', '💩', '👾', '🎮'
      // ]
    }
  },
  
  computed: {
    // 表情面板网格布局
    // emojiRows() {
    //   const rows = []
    //   const cols = 8
    //   for (let i = 0; i < this.emojiList.length; i += cols) {
    //     rows.push(this.emojiList.slice(i, i + cols))
    //   }
    //   return rows
    // },
    
    // 确认按钮类型
    confirmType() {
      return this.emojiPanelVisible ? 'send' : 'done'
    }
  },
  
  onLoad(options) {
    // 获取目标用户ID
    const userId = options.userId
    
    // 初始化数据
    this.initData(userId)
    
    // 设置内容区域高度
    this.setContentHeight()
    
    // 监听键盘高度变化
    this.listenKeyboardHeight()
  },
  
  onReady() {
    // 页面初次加载完成后滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom()
    })
  },
  
  onShow() {
    // 显示页面时检查用户状态
    this.checkUserStatus()
  },
  
  onUnload() {
    // 移除键盘监听
    uni.offKeyboardHeightChange()
  },
  
  methods: {
    // 初始化数据
    initData(userId) {
      // 获取目标用户信息
      this.targetUser = this.getUserInfo(userId)
      
      // 获取当前用户信息
      this.currentUser = this.getCurrentUserInfo()
      
    //   // 加载聊天消息
      this.loadChatMessages()
      
      // 设置当前日期
      this.currentDate = this.getFormattedDate()
    },
    
    // 获取用户信息
    getUserInfo(userId) {
      // 从模拟数据中获取用户信息
      const user = mockChatData.users.find(u => u.id === parseInt(userId))
      return user || {
        id: userId,
        nickname: '未知用户',
        avatar: 'https://picsum.photos/id/237/200/200',
        isOnline: false,
        lastOnline: '未知'
      }
    },
    
    // 获取当前用户信息
    getCurrentUserInfo() {
      // 从模拟数据中获取当前用户信息
      return mockChatData.currentUser
    },
    
    // 加载聊天消息
    loadChatMessages() {
      // 获取当前用户ID和目标用户ID
      const currentUserId = this.currentUser.id
      const targetUserId = this.targetUser.id
      
      // 从模拟数据中获取聊天记录
      const messages = mockChatData.chatMessages
	  // .filter(msg => {
   //      return (msg.senderId === currentUserId && msg.receiverId === targetUserId) ||
   //             (msg.senderId === targetUserId && msg.receiverId === currentUserId)
   //    })
      
      // 按时间排序
      messages.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
      
      // 设置消息列表
      this.messageList = messages
      
      // 标记消息为已读
      this.markMessagesAsRead()
    },
    
    // 加载更多历史消息
    async loadMoreMessages() {
      if (this.loadingHistory || !this.hasMoreHistory) return
      
      this.loadingHistory = true
      
      try {
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 假设这里有更多历史消息
        const moreMessages = []
        
        if (moreMessages.length > 0) {
          // 在消息列表前面添加历史消息
          this.messageList = [...moreMessages, ...this.messageList]
          this.page++
        } else {
          this.hasMoreHistory = false
        }
      } catch (error) {
        console.error('加载历史消息失败', error)
      } finally {
        this.loadingHistory = false
      }
    },
    
    // 发送消息
    sendMessage() {
      const content = this.inputMessage.trim()
      if (!content) return
      
      // 创建新消息
      const newMessage = {
        id: `msg_${Date.now()}`,
        senderId: this.currentUser.id,
        receiverId: this.targetUser.id,
        content: content,
        timestamp: new Date().toISOString(),
        status: 'sending',
        type: 'text'
      }
      
      // 添加到消息列表
      this.messageList.push(newMessage)
      
      // 清空输入框
      this.inputMessage = ''
      
      // 滚动到底部
      this.scrollToBottom()
      
      // 模拟发送消息
      this.simulateSendMessage(newMessage)
    },
    
    // 模拟发送消息
    simulateSendMessage(message) {
      // 模拟API请求延迟
      setTimeout(() => {
        // 随机决定是否发送失败
        const success = Math.random() > 0.1
        
        if (success) {
          // 发送成功，更新消息状态
          const index = this.messageList.findIndex(msg => msg.id === message.id)
          if (index !== -1) {
            this.$set(this.messageList[index], 'status', 'sent')
          }
        } else {
          // 发送失败，更新消息状态
          const index = this.messageList.findIndex(msg => msg.id === message.id)
          if (index !== -1) {
            this.$set(this.messageList[index], 'status', 'failed')
          }
        }
      }, 800)
    },
    
    // 重试发送消息
    retrySendMessage(message) {
      // 更新消息状态为发送中
      const index = this.messageList.findIndex(msg => msg.id === message.id)
      if (index !== -1) {
        this.$set(this.messageList[index], 'status', 'sending')
      }
      
      // 重新发送
      this.simulateSendMessage(message)
    },
    
    // 标记消息为已读
    markMessagesAsRead() {
      // 模拟标记消息为已读的API调用
      // 实际项目中应该调用后端API
    },
    
    // 检查用户状态
    checkUserStatus() {
      // 模拟检查用户在线状态的API调用
      // 实际项目中应该调用后端API
    },
    
    // 插入表情
    insertEmoji(emoji) {
      this.inputMessage += emoji
    },
    
    // 切换表情面板
    toggleEmojiPanel() {
      this.emojiPanelVisible = !this.emojiPanelVisible
      
      // 如果表情面板显示，隐藏键盘
      if (this.emojiPanelVisible) {
        uni.hideKeyboard()
      }
      
      // 调整滚动位置
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: (res) => {
          // 发送图片消息
          this.sendImageMessage(res.tempFilePaths[0])
        }
      })
    },
    
    // 拍照
    takePhoto() {
      const cameraContext = uni.createCameraContext()
      cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          // 发送图片消息
          this.sendImageMessage(res.tempImagePath)
        }
      })
    },
    
    // 发送图片消息
    sendImageMessage(imagePath) {
      // 创建图片消息
      const imageMessage = {
        id: `msg_${Date.now()}`,
        senderId: this.currentUser.id,
        receiverId: this.targetUser.id,
        content: imagePath,
        timestamp: new Date().toISOString(),
        status: 'sending',
        type: 'image'
      }
      
      // 添加到消息列表
      this.messageList.push(imageMessage)
      
      // 滚动到底部
      this.scrollToBottom()
      
      // 模拟发送图片消息
      this.simulateSendMessage(imageMessage)
    },
    
    // 输入框聚焦
    onInputFocus() {
      // 隐藏表情面板
      this.emojiPanelVisible = false
    },
    
    // 监听键盘高度变化
    listenKeyboardHeight() {
      uni.onKeyboardHeightChange(res => {
        this.keyboardHeight = res.height
        
        // 键盘弹出时滚动到底部
        if (res.height > 0) {
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      })
    },
    
    // 设置内容区域高度
    setContentHeight() {
      // 获取窗口高度
      const windowHeight = uni.getSystemInfoSync().windowHeight
      
      // 计算内容区域高度 (窗口高度 - 导航栏高度 - 输入区域高度)
      this.contentHeight = windowHeight - 100
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.chat-content').boundingClientRect()
        query.select('.message-list').boundingClientRect()
        query.exec(res => {
          if (res[0] && res[1]) {
            this.scrollTop = res[1].height - res[0].height
          }
        })
      })
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    },
    
    // 获取格式化日期
    getFormattedDate() {
      const date = new Date()
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}年${month}月${day}日`
    },
    
    // 判断是否显示时间戳
    showTimestamp(index) {
      // 第一条消息总是显示时间戳
      if (index === 0) return true
      
      const currentMessage = this.messageList[index]
      const prevMessage = this.messageList[index - 1]
      
      // 如果是不同发送者，显示时间戳
      if (currentMessage.senderId !== prevMessage.senderId) return true
      
      // 如果时间间隔超过5分钟，显示时间戳
      const currentTime = new Date(currentMessage.timestamp).getTime()
      const prevTime = new Date(prevMessage.timestamp).getTime()
      const timeDiff = currentTime - prevTime
      
      return timeDiff > 5 * 60 * 1000
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转到用户详情页
    goToUserDetail() {
      uni.navigateTo({
        url: `/pages/userDetail/userDetail?userId=${this.targetUser.id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  position: relative;
  background-color: #f8f8f8;
}

.custom-nav {
  height: 50px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-info {
  flex: 1;
  display: flex;
  align-items: center;
  padding-left: 10px;
}

.avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-right: 10px;
}

.name-info {
  display: flex;
  flex-direction: column;
}

.name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.status {
  font-size: 12px;
  color: #999;
}

.more-btn {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chat-content {
  position: relative;
  overflow-y: auto;
}

.date-separator {
  text-align: center;
  margin: 15px 0;
}

.date-separator text {
  padding: 5px 15px;
  background-color: rgba(0, 0, 0, 0.1);
  color: #fff;
  font-size: 12px;
  border-radius: 15px;
}

.message-list {
  padding: 0 15px;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  position: relative;
}

.message-item.other {
  justify-content: flex-start;
}

.message-item.mine {
  justify-content: flex-end;
}

.message-item.show-timestamp {
  margin-top: 25px;
}

.timestamp {
  position: absolute;
  top: -18px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #999;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.message-item.other .avatar {
  margin-right: 10px;
}

.message-item.mine .avatar {
  margin-left: 10px;
}

.message-content {
  max-width: 70%;
  position: relative;
}

.bubble {
  padding: 10px 15px;
  border-radius: 18px;
  font-size: 15px;
  position: relative;
  word-break: break-all;
}

.message-item.other .bubble {
  background-color: #fff;
  color: #333;
}

.message-item.mine .bubble {
  background-color: #FF4500;
  color: #fff;
}

.status {
  position: absolute;
  right: -20px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-history,
.no-more-history {
  text-align: center;
  padding: 10px 0;
  font-size: 13px;
  color: #999;
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  border-top: 1px solid #eee;
  transition: bottom 0.3s;
}

.toolbar {
  display: flex;
  width: 80px;
}

.tool-btn {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.input-box {
  flex: 1;
  height: 35px;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 0 15px;
  display: flex;
  align-items: center;
}

.input-box input {
  flex: 1;
  height: 100%;
  font-size: 15px;
  color: #333;
}

.send-btn {
  width: 60px;
  height: 35px;
  line-height: 35px;
  text-align: center;
  background-color: #FF4500;
  color: #fff;
  border-radius: 20px;
  margin-left: 10px;
  font-size: 14px;
}

.emoji-panel {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  height: 200px;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 15px;
  display: flex;
  flex-direction: column;
  transition: bottom 0.3s;
}

.emoji-row {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.emoji-item {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}
</style>
